package com.example.helpconnect;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.example.controller.SMSUtility;
import com.example.controller.Service;
import com.example.controller.ServiceStatus;
import com.example.controller.User;
import com.example.model.ServiceCRUD;
import com.example.model.ServiceStatusCRUD;
import com.example.model.UserCRUD;

public class OfferedServicesActivity extends Activity {

    User user;
    Service service;
    List<Service> offeredServices;
    ArrayAdapter<Service> adapter;
    
    CostTextWatcher costFieldWatcher = new CostTextWatcher();
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.offered_services);
		
    	//Add these two lines to disable StrictMode
    	StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    	StrictMode.setThreadPolicy(policy); 
		
		Intent i = getIntent();
		i.getStringExtra("key");
		int userID = i.getIntExtra("userID", -1);
		user = new User(new UserCRUD());		
		user = user.read(userID);
		
		service = new Service(new ServiceCRUD());
		
		offeredServices = service.readAllByUser(user.getUserID());
		
		adapter = new ArrayAdapter<Service>(getApplicationContext(), R.layout.simple_list_item, offeredServices);
		
		ListView listView = (ListView)findViewById(R.id.offeredServicesList);
		listView.setEmptyView(findViewById(R.id.noOfferedServicesText));
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				onSelectService((Service) parent.getItemAtPosition(position));
			}
		});
		
		Button addButton = (Button)findViewById(R.id.offerServiceBtn);
		addButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				onAddService();
			}
		});
	}
	
	private void onSelectService(Service srv) {
		setContentView(R.layout.offered_service_edit);
		service = srv;
		
		findViewById(R.id.deleteOfferedServiceBtn).setVisibility(View.VISIBLE);
		findViewById(R.id.connectionList).setVisibility(View.VISIBLE);
		findViewById(R.id.noOfferedServiceRequestsText).setVisibility(View.VISIBLE);
		setCostFormat();
		
		final List<ServiceStatus> statuses = new ArrayList<ServiceStatus>();
		final List<String> statusStrs = new ArrayList<String>();		
		final ArrayAdapter<String> statusAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.simple_list_item, statusStrs);
		populateServiceStatuses(service.getServiceID(), statuses, statusStrs, statusAdapter);
		
		ListView listView = (ListView)findViewById(R.id.connectionList);
		listView.setEmptyView(findViewById(R.id.noOfferedServiceRequestsText));
		listView.setAdapter(statusAdapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				final ServiceStatus ss = statuses.get(position);
				User requester = new User(new UserCRUD());
				requester = requester.read(ss.getRequesterUserID());
				
				if (ss.isPaid() || ss.isConnected())
					return;
				
				new AlertDialog.Builder(OfferedServicesActivity.this)
				.setIcon(android.R.drawable.ic_dialog_alert)
				.setTitle("Respond to Request")
				.setMessage("Do you want to help " + requester.getFirstName() + " with " + service.getDescription() + "?")
				.setNegativeButton("Reject", new DialogInterface.OnClickListener() {					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						ss.delete();
						populateServiceStatuses(ss.getServiceID(), statuses, statusStrs, statusAdapter);
						dialog.dismiss();
					}
				})
				.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {						
					@Override
					public void onClick(DialogInterface dialog, int which) {
						ss.setConnected(true);
						ss.update();
						
						User owner = new User(new UserCRUD());
						owner = owner.read(ss.getServiceOwnerID());
						
						String message = "**HelpConnect Message**\n";
				    	message += owner.getFirstName() + " " + owner.getLastName() + " has agreed to help you with " + service.getDescription() + ".";
				    	
				    	SMSUtility smsTool = new SMSUtility(ss.getRequesterUserID(), message);
				    	smsTool.sendSMS();
						
						populateServiceStatuses(ss.getServiceID(), statuses, statusStrs, statusAdapter);
						dialog.dismiss();
					}
				})
				.show();
			}
		});
		
		EditText descriptionText = (EditText)findViewById(R.id.offeredServiceDescription);
		EditText costText = (EditText)findViewById(R.id.offeredServiceCost);
		
		descriptionText.setText(service.getDescription());
		costText.setText(NumberFormat.getCurrencyInstance().format(service.getCost()));
		
		Button cancelBtn = (Button)findViewById(R.id.cancelOfferedServiceBtn);
		cancelBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
            	returnToActivity();           
            }		
        });
		
		Button saveBtn = (Button)findViewById(R.id.saveOfferedServiceBtn);
		saveBtn.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				String description = ((EditText)findViewById(R.id.offeredServiceDescription)).getText().toString();
				service.setDescription(description);
				
				NumberFormat currency = NumberFormat.getCurrencyInstance();
				String costText = ((EditText)findViewById(R.id.offeredServiceCost)).getText().toString();
				try {
					service.setCost(currency.parse(costText).doubleValue());
				} catch (ParseException e) {
					e.printStackTrace();
					returnToActivity();
					return;
				}
			
				service.update();
				
				offeredServices = service.readAllByUser(user.getUserID());
				adapter.notifyDataSetChanged();
				returnToActivity();
			}
		});
		
		Button deleteBtn = (Button)findViewById(R.id.deleteOfferedServiceBtn);
		deleteBtn.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				new AlertDialog.Builder(OfferedServicesActivity.this)
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setTitle("Delete Service")
					.setMessage("Are you sure you want to delete the service?:\n" + service.getDescription())
					.setNegativeButton("No", null)
					.setPositiveButton("Yes", new DialogInterface.OnClickListener() {						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							service.delete();
							
							offeredServices = service.readAllByUser(user.getUserID());
							adapter.notifyDataSetChanged();
							returnToActivity();
						}
					})
					.show();
			}
		});
	}
	
	private void onAddService() {
		setContentView(R.layout.offered_service_edit);
		
		findViewById(R.id.deleteOfferedServiceBtn).setVisibility(View.GONE);
		findViewById(R.id.connectionList).setVisibility(View.GONE);
		findViewById(R.id.noOfferedServiceRequestsText).setVisibility(View.GONE);
		setCostFormat();
		
		Button cancelBtn = (Button)findViewById(R.id.cancelOfferedServiceBtn);
		cancelBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
            	returnToActivity();           
            }		
        });
		
		Button saveBtn = (Button)findViewById(R.id.saveOfferedServiceBtn);
		saveBtn.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				String description = ((EditText)findViewById(R.id.offeredServiceDescription)).getText().toString();
				service.setDescription(description);
				
				NumberFormat currency = NumberFormat.getCurrencyInstance();
				String costText = ((EditText)findViewById(R.id.offeredServiceCost)).getText().toString();
				if (costText.isEmpty()) {
					service.setCost(0);
				} else {
					try {
						service.setCost(currency.parse(costText).doubleValue());
					} catch (ParseException e) {
						e.printStackTrace();
						returnToActivity();
						return;
					}
				}
				
				service.setUserID(user.getUserID());
				service.create();
				
				offeredServices = service.readAllByUser(user.getUserID());
				adapter.notifyDataSetChanged();
				returnToActivity();
			}
		});
	}
	
	private void setCostFormat() {
		final EditText costField = (EditText)findViewById(R.id.offeredServiceCost);
		costField.removeTextChangedListener(costFieldWatcher);
		costFieldWatcher.setCostField(costField);
		costField.addTextChangedListener(costFieldWatcher);
	}
	
	private void populateServiceStatuses(int serviceID, List<ServiceStatus> statuses, List<String> statusStrs, ArrayAdapter<String> statusAdapter) {
		statuses.clear();
		statusStrs.clear();
		
		ServiceStatus status = new ServiceStatus(new ServiceStatusCRUD());
		statuses.addAll(status.readAllStatusesForService(serviceID));
		
		for (ServiceStatus ss : statuses) {
			User requester = new User(new UserCRUD());
			requester = requester.read(ss.getRequesterUserID());
			if (ss.isPaid())
				statusStrs.add(requester.getFirstName() + " paid for this service at " + ss.getTimeStamp());
			else if (ss.isConnected())
				statusStrs.add("You approved " + requester.getFirstName() + "'s request at " + ss.getTimeStamp());
			else
				statusStrs.add(requester.getFirstName() + " requested this service at " + ss.getTimeStamp());
		}
		
		statusAdapter.notifyDataSetChanged();
	}

	private void returnToActivity() {
		Intent offeredServicesPage = new Intent(getApplicationContext(), OfferedServicesActivity.class);
        offeredServicesPage.putExtra("userID", user.getUserID());    	            
        startActivity(offeredServicesPage);
        finish();	 
	}
}
